<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @ChangeFilter="ChangeFilter" />
      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sortChange="sortChange" />
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id">
            <GoodsItem :goodsItem="item" />
          </li>
        </ul>
        <!-- loading动画 -->
        <XtxInfiniteLoading
          @infinite="getData"
          :loading="loading"
          :finished="finished"
        ></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, reactive } from 'vue'
import { useRoute } from 'vue-router'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
import { findSubCategoryGoods } from '@/api/category'
export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    GoodsItem
  },
  setup() {
    // 商品列表数据
    const goodsList = ref([])
    // 加载中
    const loading = ref(false)
    // 加载完成
    const finished = ref(false)
    // 请求携带数据
    let reqParams = reactive({
      page: 1,
      pageSize: 20
    })
    const route = useRoute()
    const getData = () => {
      reqParams.categoryId = route.params.id
      loading.value = true
      findSubCategoryGoods(reqParams).then(data => {
        if (data.result.items.length != 0) {
          goodsList.value.push(...data.result.items)
          reqParams.page++
          loading.value = false
        } else {
          finished.value = true
        }
      })
    }
    // 切换二级分类重新加载
    watch(
      () => route.params.id,
      newVal => {
        if (newVal && `/category/sub/${newVal}` === route.path) {
          finished.value = false
          goodsList.value = []
          reqParams = {
            page: 1,
            pageSize: 20
          }
        }
      }
    )
    // 当更改排序组件数据发生改变时发起请求
    const sortChange = sortParams => {
      finished.value = false
      reqParams = { ...reqParams, ...sortParams }
      reqParams.page = 1
      goodsList.value = []
    }
    // 更改筛选区域数据发起请求
    const ChangeFilter = filterParams => {
      finished.value = false
      reqParams = { ...reqParams, ...filterParams }
      reqParams.page = 1
      goodsList.value = []
    }
    return {
      goodsList,
      loading,
      finished,
      getData,
      sortChange,
      ChangeFilter
    }
  }
}
</script>
, XtxCheckbox
<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
